﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;

namespace Updater
{
    public partial class FormUpdater : Form
    {
        public FormUpdater()
        {
            InitializeComponent();
        }

        private void FormUpdater_Load(object sender, EventArgs e)
        {

        }

        private void FormUpdater_Shown(object sender, EventArgs e)
        {
            if (!Directory.Exists("Update\\")) return;
            String[] updatedirs = Directory.GetDirectories("Update\\");
            if (updatedirs.Length == 0) return;

            String[] files = Directory.GetFiles(updatedirs[0]);

            progressBar_progress.Maximum = files.Length;
            progressBar_progress.Value = 0;

            Invalidate();

            foreach (string file in files)
            {
                progressBar_progress.Value++;
                label_file.Text = file;
                Invalidate();

                try
                {
                    File.Copy(file, Path.GetFileName(file), true);
                }
                catch
                {
                    MessageBox.Show("An error occurred during the update, please download a fresh version of the program",
                        "WBFSSync", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }

            //------ Arquivos para apagar aqui

            if (File.Exists("DevConsole.exe")) File.Delete("DevConsole.exe"); //Agora é Console.exe
            if (Directory.Exists("Skin\\_Media")) Directory.Delete("Skin\\_Media", true);
            if (Directory.Exists("Skin\\_Skin Source")) Directory.Delete("Skin\\_Skin Source", true);
            if (Directory.Exists("Skin\\_tfs")) Directory.Delete("Skin\\_tfs", true);

            //------ Atualização de configuração

            if (File.Exists("wbfssync.ini"))
            {
                List<String> Configuration = new List<string>(File.ReadAllLines("wbfssync.ini"));
                //
                if (ContainsVariable(Configuration, "Operations.PartitionSelection") < 0)
                {
                    int l = ContainsVariable(Configuration, "Operations.ExtractScrubbed") + 1;
                    if (l <= 0) l = Configuration.Count;

                    Configuration.Insert(l++, "Operations.PartitionSelection = 0 //0 - Apenas partição de jogo, ");
                    Configuration.Insert(l++, "				  //1 - Remover partição de atualização, ");
                    Configuration.Insert(l++, "				  //2 - Todas as partições");
                }

                if (ContainsVariable(Configuration, "IgnoreDrives") < 0)
                {
                    int l = ContainsVariable(Configuration, "NoFormatDrives") + 1;
                    if (l < 0) l = Configuration.Count;

                    Configuration.Insert(l++, "");
                    Configuration.Insert(l++, "//Drives ignorados pelo programa");
                    Configuration.Insert(l++, "//");
                    Configuration.Insert(l++, "//Para cada Drive a ser excluído, adicionar a letra do drive na string IgnoreDrives");
                    Configuration.Insert(l++, "");
                    Configuration.Insert(l++, "IgnoreDrives = \"AB\"");
                }

                if (ContainsVariable(Configuration, "FormatWindowCancelText") < 0)
                {
                    int l = ContainsVariable(Configuration, "NoFormatWindow") + 1;
                    if (l < 0) l = Configuration.Count;

                    Configuration.Insert(l++, "FormatWindowCancelText = \"\"");
                }

                if (ContainsVariable(Configuration, "Operations.AutoUpdateScrubs") < 0)
                {
                    int l = ContainsVariable(Configuration, "Operations.ExtractScrubbed") + 1;
                    if (l < 0) l = Configuration.Count;

                    Configuration.Insert(l++, "Operations.AutoUpdateScrubs = 0");
                }
                //
                File.WriteAllLines("wbfssync.ini", Configuration.ToArray(), Encoding.Default);
            }

            //------

            Directory.Delete(updatedirs[0], true);
            Process.Start("WBFSSync.exe");

            Close();
        }

        private int ContainsVariable(List<String> config, String var)
        {
            for (int i = 0; i < config.Count; i++)
            {
                int eq = config[i].IndexOf('=');
                if (eq < 0) continue;

                if (String.Compare(var, config[i].Substring(0, eq).Trim(), true) == 0) 
                    return i;
            }

            return -1;
        }
    }
}
